﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LicenserProduction
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeData();
        }

        void InitializeData()
        {
            LicenserInformation.LicenseTypeEnumRow row =
                licenserInformation1.LicenseTypeEnum.NewLicenseTypeEnumRow();
            row.Code = 0;
            row.Description = Resource1.LIC_MODE_DEMO;
            licenserInformation1.LicenseTypeEnum.AddLicenseTypeEnumRow(row);

            row = licenserInformation1.LicenseTypeEnum.NewLicenseTypeEnumRow();
            row.Code = 1;
            row.Description = Resource1.LIC_MODE_NODELOCKED;
            licenserInformation1.LicenseTypeEnum.AddLicenseTypeEnumRow(row);
        }

        private void BuildTreeFromDb()
        {
            string selected = "";
            if (treeView1.SelectedNode != null)
            {
                selected = treeView1.SelectedNode.Name;
            }

            contextMenuStrip2.Items[0].Enabled = true;
            contextMenuStrip3.Items[0].Enabled = true;
            treeView1.Nodes[0].Nodes.Clear();
            TreeNode custs = treeView1.Nodes[0].Nodes.Add("CUSTS", "customers", 1,1);
            foreach (LicenserInformation.CustomerInfoRow custRow in licenserInformation1.CustomerInfo)
            {
                TreeNode custNode = custs.Nodes.Add("CUST_" + custRow.CustomerId, custRow.CustomerName, 2,2);
                custNode.Tag = custRow.CustomerId;
                DataRow[] licensesDataRows =
                    licenserInformation1.Licenses.Select("CustomerId = " + custNode.Tag);
                foreach (DataRow licRow in licensesDataRows)
                {
                    TreeNode licNode = 
                        custNode.Nodes.Add("Lic_" + licRow["LicenseId"], licRow["ProductName"].ToString(), 3,3);
                    licNode.Tag = licRow["LicenseId"];

                    DataRow[] featuresDataRows = 
                        licenserInformation1.Features.Select("LicenseId = " + licNode.Tag);
                    foreach (DataRow featureRow in featuresDataRows)
                    {
                        TreeNode featureNode = licNode.Nodes.Add(
                            "FEATURE_" + featureRow["FeatureId"], featureRow["FeatureName"].ToString(), 4,4);
                        featureNode.Tag = featureRow["FeatureId"];
                    }
                }
            }
            treeView1.ExpandAll();
            if (selected != "")
            {
               treeView1.SelectedNode = GetNodeByKey(treeView1.Nodes, selected);
            }
        }

        TreeNode GetNodeByKey(TreeNodeCollection currentLevel, string key)
        {
            if (currentLevel.ContainsKey(key))
            {
                return currentLevel[key];
            }
            else
            {
                TreeNode retValue = null;
                foreach (TreeNode node in currentLevel)
                {
                    retValue = GetNodeByKey(node.Nodes, key);
                    if (retValue != null)
                    {
                        break;
                    }
                }
                return retValue;
            }
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_bSaveNeeded)
            {
                if (MessageBox.Show(
                    "Current database is not save. Do you want to proceed and lose changes?",
                    "Database not saved", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                licenserInformation1.Clear();
                licenserInformation1.ReadXml(openFileDialog1.FileName);
                m_currDbFile = openFileDialog1.FileName;
                treeView1.Nodes[0].Text = "Database (" + m_currDbFile + ")";
                newDatabaseToolStripMenuItem.Enabled = false;
                newToolStripMenuItem.Enabled = false;
                openDatabaseToolStripMenuItem.Enabled = false;
                openToolStripMenuItem.Enabled = false;
                saveDatabaseToolStripMenuItem.Enabled = true;
                saveToolStripMenuItem.Enabled = true;
                closeDatabaseToolStripMenuItem.Enabled = true;
                closeToolStripMenuItem.Enabled = true;
                btnSave.Enabled = true;
                BuildTreeFromDb();
            }
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_currDbFile == "Untitled")
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    m_currDbFile = saveFileDialog1.FileName;
                }
                else
                {
                    m_currDbFile = openFileDialog1.FileName;
                }
            }
            licenserInformation1.WriteXml(m_currDbFile);
            treeView1.Nodes[0].Text = "Database (" + m_currDbFile + ")";
        }

        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (m_bSaveNeeded)
            {
                if (MessageBox.Show(
                    "Current database is not save. Do you want to proceed and lose changes?",
                    "Database not saved", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
                BuildTreeFromDb();
            }

            m_currDbFile = "Untitled";

            treeView1.Nodes[0].Text = "Database (Untitled)";

            newDatabaseToolStripMenuItem.Enabled = false;
            newToolStripMenuItem.Enabled = false;
            openDatabaseToolStripMenuItem.Enabled = false;
            openToolStripMenuItem.Enabled = false;
            saveDatabaseToolStripMenuItem.Enabled = true;
            saveToolStripMenuItem.Enabled = true;
            closeDatabaseToolStripMenuItem.Enabled = true;
            closeToolStripMenuItem.Enabled = true;
            btnSave.Enabled = true;
            btnSave.Enabled = true;

            BuildTreeFromDb();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            openToolStripMenuItem_Click(sender, e);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);
        }

        private void newDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newToolStripMenuItem_Click(sender, e);
        }

        private void openDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openToolStripMenuItem_Click(sender, e);
        }

        private void saveDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender, e);
        }

        string m_currDbFile = "Untitled";
        bool m_bSaveNeeded = false;

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            generateToolStripMenuItem.Enabled = false;

            if (e.Node.Name.StartsWith("CUSTS"))
            {
                CustomerData cd = new CustomerData(licenserInformation1, Int32.MaxValue);
                cd.OnSynchronize += new CustomerData._OnSynchronize(cd_OnSynchronize);
                cd.OnDataUpdate += new CustomerData._OnDataUpdate(cd_OnDataUpdate);
                splitContainer1.Panel2.Controls.Add(cd);
                treeView1.ContextMenuStrip = contextMenuStrip1;
            }
            else if (e.Node.Name.StartsWith("CUST_"))
            {
                CustomerData cd = new CustomerData(licenserInformation1, (int)e.Node.Tag);
                cd.OnSynchronize += new CustomerData._OnSynchronize(cd_OnSynchronize);
                cd.OnDataUpdate += new CustomerData._OnDataUpdate(cd_OnDataUpdate);
                splitContainer1.Panel2.Controls.Add(cd);
                cd.OnDataUpdate += new CustomerData._OnDataUpdate(cd_OnDataUpdate);
                treeView1.ContextMenuStrip = contextMenuStrip2;
            }
            else if (e.Node.Name.StartsWith("Lic_") || e.Node.Name.StartsWith("FEATURE_"))
            {
                LicenseDetails ld = new LicenseDetails(licenserInformation1, (int)e.Node.Tag);
                generateToolStripMenuItem.Enabled = true;
                splitContainer1.Panel2.Controls.Add(ld);
                treeView1.ContextMenuStrip = contextMenuStrip3;
            }
            else
            {
                treeView1.ContextMenuStrip = contextMenuStrip1;
            }
        }

        private void treeView1_BeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            if (splitContainer1.Panel2.Controls.Count > 0)
            {
                Control ctrl = splitContainer1.Panel2.Controls[0];
                splitContainer1.Panel2.Controls.Remove(ctrl) ;
                ctrl.Dispose();
                if (m_bDataUpdate)
                {
                    BuildTreeFromDb();
                    m_bDataUpdate = false;
                }
            }
        }

        void cd_OnSynchronize(object sender, EventArgs e)
        {
            BuildTreeFromDb();
        }

        void cd_OnDataUpdate(object sender, EventArgs e)
        {
            m_bDataUpdate = true ;
        }

        private void newLicenseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            newLicenseToolStripMenuItem.Enabled = false;
            AddALicense license = new AddALicense(ref licenserInformation1, (int)treeView1.SelectedNode.Tag);
            license.Synchronize += new AddALicense._Synchronize(license_Synchronize);
            splitContainer1.Panel2.Controls.Clear();
            splitContainer1.Panel2.Controls.Add(license);
        }

        void license_Synchronize(object sender, EventArgs e)
        {
            Control ctrl = splitContainer1.Panel2.Controls[0];
            splitContainer1.Panel2.Controls.Remove(ctrl);
            ctrl.Dispose();
            BuildTreeFromDb();
            m_bDataUpdate = false;
        }

        bool m_bDataUpdate = false;

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            closeDatabaseToolStripMenuItem_Click(sender, e);
        }

        private void closeDatabaseToolStripMenuItem_Click(object sender, EventArgs e)
        {
            licenserInformation1.Clear();
            InitializeData();
            treeView1.Nodes[0].Nodes.Clear();
            m_bDataUpdate = false;
            m_bSaveNeeded = false;

            newDatabaseToolStripMenuItem.Enabled = true;
            newToolStripMenuItem.Enabled = true;
            openDatabaseToolStripMenuItem.Enabled = true;
            openToolStripMenuItem.Enabled = true;
            saveDatabaseToolStripMenuItem.Enabled = false;
            saveToolStripMenuItem.Enabled = false;
            closeDatabaseToolStripMenuItem.Enabled = false;
            closeToolStripMenuItem.Enabled = false;
            btnSave.Enabled = false;

        }

        private void saveDatabaseToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender,e);
        }

        private void saveDatabaseToolStripMenuItem2_Click(object sender, EventArgs e)
        {
            saveToolStripMenuItem_Click(sender,e);
        }

        private void generateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LicenseDetails details = (LicenseDetails)splitContainer1.Panel2.Controls[0];
            details.btnGenerate_Click(sender, e);
        }

        private void GenerateLicensetoolStripMenuItem_Click(object sender, EventArgs e)
        {
            generateToolStripMenuItem_Click(sender, e);
        }

        private void testToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TestLicenseForm testForm = new TestLicenseForm();
            testForm.ShowDialog();
        }

        private void TestLictoolStripMenuItem_Click(object sender, EventArgs e)
        {
            testToolStripMenuItem_Click(sender, e);
        }

    }
}
